//识别结果，单个图片识别
<template>
  <div class="box">
    <div class="img-box">
      <br /><br />
      <!-- <router-view></router-view> -->
      <div class="shibie-file-font">所选图片:</div>
      <input
        type="file"
        style="display: none"
        ref="ref1"
        @change="onFileChange"
      />
      <div class="shibie-file-font-2">识别结果(耗时{{ time }}ms):</div>
      <br />
      <div class="img-box-childe">
        <img :src="this.$store.state.avatar" class="img-box-childe-1" />
      </div>
      <div
        class="box-echarts"
        v-loading="loading"
        element-loading-text="拼命识别中"
      >
        <div class="b" id="curve_show"></div>
      </div>
      <br /><br />
      <div
        style="
          width: 1100px;
          height: 50px;
          position: relative;
          margin-left: 30px;
        "
      >
        <el-checkbox
          class="checkbox"
          style="position: absolute"
          v-model="checked"
        />
        <p
          style="
            display: inline-block;
            margin-left: 10px;
            position: relative;
            left: 170px;
            top: -20px;
          "
        >
          裁剪图片
        </p>
        &nbsp;
        <button
          @click="btn"
          style="
            width: 90px;
            height: 36px;
            border: 0px;
            background-color: #54924b;
            font-size: 17px;
            color: aliceblue;
            position: relative;
            margin-left: 170px;
            margin-top: -50px;
            bottom: 17px;
          "
        >
          重新上传
        </button>
      </div>

      <hr />
    </div>
    <!-- 引用组件 -->
    <avatar-cropper
      :dialogVisible.sync="dialogVisible"
      @closeAvatarDialog="closeAvatarDialog"
    ></avatar-cropper>
    <router-view></router-view>
  </div>
</template>
<script>
import * as echarts from "echarts";
import { predict_single } from "@/api/index";
import avatarCropper from "@/components/avatarCropper";
export default {
  data() {
    return {
      checked: false,
      dialogVisible: false,
      disease: [],
      probability: [],
      time: 0,
      loading: true,
      myChart: {},
    };
  },
  components: {
    avatarCropper,
  },
  created() {
    this.$router.push("/shibie/shibieFile/appleDesease");
  },
  mounted() {
    this.myChart = echarts.init(document.getElementById("curve_show"));

    this.initFn();
  },
  methods: {
    btn() {
      //打开识别
      if (this.checked) {
        //勾选了图片裁剪
        //打开弹窗
        this.dialogVisible = true;
      } else {
        this.$refs.ref1.click(); // 模拟点击
      }
    },
    //关闭弹窗时，即在弹窗点击确认时
    closeAvatarDialog(data) {
      // console.log(data);
      this.dialogVisible = false;
      let file = this.base64ToFile(data, "image");
      // console.log(file);
      if (file) {
        // 选择了图片
        this.avatar = URL.createObjectURL(file);
        this.$store.commit("avatar", this.avatar);
        this.$store.commit("setData", file);
        this.$refs.ref1.value = ""; //清空input的value，避免重复选择，而选择不上
        this.initFn();
      }
    },
    base64ToFile(data, fileName) {
      const dataArr = data.split(",");
      const byteString = atob(dataArr[1]);
      const options = {
        type: "image/jpeg",
        endings: "native",
      };
      const u8Arr = new Uint8Array(byteString.length);
      for (let i = 0; i < byteString.length; i++) {
        u8Arr[i] = byteString.charCodeAt(i);
      }
      let file = new File([u8Arr], fileName + ".jpg", options); //返回文件流
      return file;
    },
    onFileChange(e) {
      const files = e.target.files;
      if (files.length > 0) {
        this.avatar = URL.createObjectURL(files[0]);
        this.$store.commit("avatar", this.avatar); //是否显示图片
        this.$store.commit("setData", files[0]);
        this.$refs.ref1.value = ""; //清空input的value，避免重复选择，而选择不上
        this.initFn();
      }
    },
    async initFn() {
      let file = this.$store.state.imgs; //此时file是文件对象，而不是数组
      if (file != null) {
        //开启loading（转圈）效果
        this.loading = true;
        var form = new FormData();
        form.append("file", file);
        //识别开始时间
        let startTime = new Date().getTime();

        await predict_single(form).then((res) => {
          //识别结束时间
          let endTime = new Date().getTime();
          //耗时
          this.time = endTime - startTime;

          // console.log("predict_single===========" + JSON.stringify(res.data));
          let result = JSON.parse(JSON.stringify(res.data));

          if (result.code == 0) {
            this.disease = result.data.disease;
            this.probability = result.data.probability;
            //存储病害名称，以便于请求后端展示病害详情
            this.$store.commit("setDisease", this.disease[0]);
            //更新统计图
            this.initCurve();
            //关闭loading（转圈）效果
            this.loading = false;
            this.$notify.success({
              title: "Info",
              message: "识别成功！",
              showClose: false,
            });
          } else {
            this.$notify.error({
              title: "错误",
              message: result.message,
            });
          }
        });
      } else {
        this.$notify.error({
          title: "错误",
          message: "图片丢失！",
        });
      }
    },
    // 初始化统计图
    initCurve() {
      // var myChart = echarts.init(document.getElementById("curve_show"));
      this.myChart.setOption({
        title: {
          text: "Top3 病害预测结果",
          left: "center",
        },
        color: ["#54924b", "#54924b", "#54924b"],
        tooltip: {},
        xAxis: {
          name: "病害",
          data: this.disease,
        },
        yAxis: {
          type: "value",
          name: "置信度",
        },
        series: [
          {
            name: "比例",
            type: "bar",
            data: this.probability,
            barWidth: "50%",
            showBackground: true,
            backgroundStyle: {
              color: "rgba(180, 180, 180, 0.2)",
            },
            label: {
              show: true, //开启显示
              position: "top", //在上方显示
              formatter: "{c}%",
              textStyle: {
                //数值样式
                color: "black",
                fontSize: 12,
              },
            },
            // itemStyle: {
            //   normal: {
            //     label: {
            //       show: true, //开启显示
            //       position: "top", //在上方显示
            //       formatter: "{c}%",
            //       textStyle: {
            //         //数值样式
            //         color: "black",
            //         fontSize: 12,
            //       },
            //     },
            //   },
            // },
          },
        ],
      });
    },
  },
};
</script>
<style scoped>
.box {
  width: 1200px;
  height: 400px;
}
.img-box {
  width: 1200px;
  height: 400px;
  /* background: rgb(255, 15, 55); */
  /* margin-left: 120px; */
  /* padding-top: 10px; */
  /* float: rght; */
  display: inline-block;
}
.img-box-childe {
  width: 280px;
  height: 300px;
  background-color: rgb(232, 233, 232);
  margin-left: 150px;
  display: inline-block;
  margin-top: -30px;
}
.img-box-childe-1 {
  width: 280px;
  height: 300px;
  /* background-color: rgb(30, 126, 210); */
  display: inline-block;
  /* margin-top: -70px; */
}
.checkbox {
  width: 80px;
  height: 20px;
  /* background-color: aquamarine; */
  margin-left: 160px;
  /* margin-top: 10px; */
}
.box-echarts {
  width: 500px;
  height: 300px;
  background-color: rgb(232, 233, 232);
  /* float: right; */
  /* display:inline-block; */
  display: inline-block;
  margin-left: 130px;
}
.b {
  width: 500px;
  height: 300px;
  margin-top: 30px;
}
.shibie-file-font {
  margin-left: 150px;
  font-size: 30px;
  color: rgb(7, 8, 6);
  display: inline-block;
}
.shibie-file-font-2 {
  margin-left: 280px;
  font-size: 30px;
  color: rgb(7, 8, 6);
  display: inline-block;
}
.desease {
  width: 200px;
  height: 200px;
  background-color: aqua;
}
.xiangqing {
  margin-top: -60px;
}
</style>
